package com.woniu.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 含注解的切面类，定义通知
 *
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/8/22 16:58
 */
@Aspect//定义切面类注解
@Component
public class AspectJavaAnnotation {
    /*配置内部的切入点表达式
     * @Author: WenXin
     * @Datetime: 2022/8/23 15:14
     * @Params:
     * @Return:
     **/
    @Pointcut("execution(* com.woniu.service.*.*(..))")
    private void myPointCut() {
    }

    @Pointcut("execution(* com.woniu.service.*.findOne(..))")
    private void myAroundPointCut() {
    }

    //前置通知
    @Before("myPointCut()")
    public void myBefore(JoinPoint joinPoint) {
        System.out.println("前置通知！模拟事务的开启");
        System.out.println("获取目标类：" + joinPoint.getTarget());
        System.out.println("获取目标方法：" + joinPoint.getSignature().getName());
        System.out.println("前置通知结束-------------------------");
    }

    //后置通知
    @AfterReturning("myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.println("后置通知！模拟事务的提交！");
        System.out.println("获取目标方法：" + joinPoint.getSignature().getName());
        System.out.println("后置通知结束--------------------------");
    }

    /*环绕通知
     * @Author: WenXin
     * @Datetime: 2022/8/23 11:49
     * @Params:
     * @Return:
     **/
    @Around("myAroundPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知开始");
        //可以获取入参
        Object[] args = joinPoint.getArgs();
        //进行传参,类似反射的执行invoke方法，拦截方法并执行
        Object proceed = joinPoint.proceed(args);
        System.out.println(proceed);
        System.out.println("环绕通知结束！");
        return proceed;
    }

    //最终通知
    @After("myPointCut()")
    public void myAfter(JoinPoint joinPoint) {
        System.out.println("最终通知无论什么情况都会执行----------------");
    }

    //异常通知,需要配置异常对象
    @AfterThrowing(value = "myPointCut()", throwing = "e")
    public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
        System.out.println("异常的信息为：" + e.getMessage());
        System.out.println("异常通知执行结束----------------");
    }
}
